package com.ecommerce.dal.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.ecommerce.dal.dao.IItemDAO;
import com.ecommerce.dal.entity.Item;
import com.ecommerce.dal.util.CustomHibernateDAOSupport;

@Repository("itemDAO")
public class ItemDAO extends CustomHibernateDAOSupport implements IItemDAO {

	@Override
	public void save(Item item) {
		getHibernateTemplate().save(item);

	}

	@Override
	public void update(Item item) {
		getHibernateTemplate().update(item);

	}

	@Override
	public void delete(Item item) {
		getHibernateTemplate().delete(item);

	}

	@Override
	public Item findByItemId(long itemId) {
		List list = getHibernateTemplate().find(
				"from Item item where item.itemId=?", itemId);
		return (Item) ((list != null && list.size()>0) ?  list.get(0) : null) ;
	}

	@Override
	public List<Item> findItemByCategory(long categoryId) {
		List list = getHibernateTemplate().find(
				"select item from Item item inner join item.category category where category.categoryId=?", categoryId);
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Item> findItemByClientId(long clientId) {
		List list = getHibernateTemplate().find(
				"select item from Item item inner join item.client client inner join client.user user where user.userId =?", clientId);
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Item> findDiscountedItems() {
		List list = getHibernateTemplate().find(
				"from Item item where item.itemDiscount > 0");
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Item> findItemByDiscount(Double minDiscount, Double maxDiscount) {
		List list = getHibernateTemplate().find(
				"from Item item where item.itemDiscount between ? and ?",
				minDiscount, maxDiscount);
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Item> findItemByClientUserName(String clientUsername) {

		List list = getHibernateTemplate()
				.find("select item from Item item inner join item.client client inner join client.user user where user.userName = ?",
						clientUsername);
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Item> findItemByCompany(long companyId) {
		List list = getHibernateTemplate()
				.find("select item from Item item inner join item.client client inner join client.company company where company.companyId = ?",
						companyId);
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<Item> findItemByPrice(Double minPrice, Double maxPrice) {
		List list = getHibernateTemplate()
				.find("from Item item where item.itemPrice between ? and ? order by item.itemPrice asc",
						minPrice, maxPrice);
		return ((list != null && list.size()>0) ?  list : null) ;
	}

}
